package com.bignerdranch.android.expresshelper.Activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.Response;
import com.bignerdranch.android.expresshelper.Adapter.CompanyListAdapter;
import com.bignerdranch.android.expresshelper.R;
import com.bignerdranch.android.expresshelper.Utils.CheckNet;
import com.bignerdranch.android.expresshelper.Utils.RequestUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class DialogActivity extends AppCompatActivity implements View.OnClickListener {
    private String url = "http://route.showapi.com/64-20?showapi_appid=20076&showapi_sign=b697ebeae51b4525b7ea856bade2d325&maxSize=60";
    private ListView mListView;
    private CompanyListAdapter mAdapter;
    private String simName;
    private String imgUrl;
    private LinearLayout progress;
    private Button refresh;
    private LinearLayout wifi;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_list);
        initView();

        if (CheckNet.getNet(getApplicationContext())){
            initResult();
        }else {
            progress.setVisibility(View.INVISIBLE);
            wifi.setVisibility(View.VISIBLE);
            mListView.setVisibility(View.INVISIBLE);
        }
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TextView v = (TextView) view.findViewById(R.id.company_sim);
                TextView v2 = (TextView) view.findViewById(R.id.company_name);

                simName = v.getText().toString();
                String expName = v2.getText().toString();
                Log.e("============getUrl=", position + "");
                saveImage(mAdapter.getUrl(position), simName);

                Intent i = new Intent();

                i.putExtra("simName", simName);
                i.putExtra("Name", expName);
                setResult(RESULT_OK, i);
                finish();
            }
        });

    }

    private void initResult() {
        RequestUtil.executeJSONObject(this, url, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject o) {
                try {
                    progress.setVisibility(View.INVISIBLE);
                    wifi.setVisibility(View.INVISIBLE);
                    mListView.setVisibility(View.VISIBLE);
                    mAdapter = new CompanyListAdapter(getApplicationContext(), o.getJSONObject("showapi_res_body")
                            .getJSONArray("expressList"));
                    mListView.setAdapter(mAdapter);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });


    }

    private void initView() {
        progress = (LinearLayout) findViewById(R.id.progress);
        refresh = (Button) findViewById(R.id.refresh);
        wifi = (LinearLayout) findViewById(R.id.wifi);
        mListView = (ListView) this.findViewById(R.id.listView);
        refresh.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.refresh:
                initResult();
                break;
        }
    }

    public void saveImage(final String imgUrl, final String simName) {
        new Thread() {
            @Override
            public void run() {
                super.run();

                try {
                    URL url = new URL(imgUrl);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    // connection.setDoOutput(true);
                    connection.setDoInput(true);
                    connection.setConnectTimeout(3000);
                    connection.setReadTimeout(3000);

                    if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                        InputStream input = connection.getInputStream();//拿到网络流
                        File file = new File(getFilesDir(), simName + ".jpg");

                        OutputStream output = new FileOutputStream(file);
                        int len = -1;
                        byte[] b = new byte[1024 * 100];
                        while ((len = input.read(b, 0, 1024 * 100)) != -1) {
                            output.write(b, 0, len);
                        }
                        output.flush();
                        output.close();
                        input.close();
                    }


                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();


    }


}
